package com.yxuan.springboot.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yxuan.springboot.model.ProfessionalScore;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/ESController")
public class ESController {

    @Autowired
    private RestTemplate restTemplate;

    @ApiOperation(value = "查询所有", notes = "查询所有反馈")
    @ResponseBody
    @GetMapping("/getall")
    public String getAll() {
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 构建请求体
        String requestBody = "{\"size\":100,\"query\":{\"range\":{\"lowest_order\":{\"lt\":109228,\"gt\":72830}}}}";

        // 发送POST请求
        String url = "http://115.231.235.17:9200/professional_score/_search";
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);

        // 处理响应结果
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            String responseBody = responseEntity.getBody();
//            System.out.println(responseBody);

            // JSON解析
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode jsonNode = objectMapper.readTree(responseBody);

                JsonNode hitsNode = jsonNode.path("hits");
                JsonNode hitsArrayNode = hitsNode.path("hits");
                List<ProfessionalScore> professionalScoreList = null;
                for (JsonNode hitNode : hitsArrayNode) {
                    JsonNode sourceNode = hitNode.path("_source");
//                    System.out.println(sourceNode);

                    ProfessionalScore professionalScore = objectMapper.convertValue(sourceNode,ProfessionalScore.class);
                    System.out.println(professionalScore);
                    professionalScoreList.add(professionalScore);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
